package controllers

import (
	"coinsend/models"
	"fmt"

	"strconv"

	"github.com/astaxie/beego"
)

// Operations about Users
type ActiveController struct {
	beego.Controller
}

//获取待签名串
// @router /getunsigne [post]
func (c *ActiveController) Getunsigne() {

	var ret models.Response

	Symbol := c.GetString("Symbol")
	From := c.GetString("From")
	To := c.GetString("To")
	Amount, err := strconv.ParseFloat(c.GetString("Amount"), 64)

	if err != nil || Symbol == "" || From == "" || To == "" || Amount <= 0 {
		ret.Code = 1
		ret.Msg = "获取待签名串失败,参数错误"
		c.Data["json"] = ret
		c.ServeJSON()
		return
	}
	beego.Debug("转账广播", Symbol, "From:", From, "to:", To, "Amount:", Amount)
	unsigne, err3 := models.GetActiveUnsigne(Symbol, From, To, Amount)
	if err3 != nil {

		ret.Code = 1
		ret.Msg = err3.Error()
		c.Data["json"] = ret
		c.ServeJSON()
		return
	}
	beego.Debug("获取待签名串", Symbol, From, To, Amount, unsigne, err3)
	ret.Code = 0
	ret.Msg = "获取待签名串成功"
	ret.Data = map[string]interface{}{
		"Unsigne": unsigne,
	}
	c.Data["json"] = ret
	c.ServeJSON()
}

//广播
// @router /sendsigned [post]
func (c *ActiveController) Sendsigned() {

	var ret models.Response

	Symbol := c.GetString("Symbol")
	To := c.GetString("To")
	Signed := c.GetString("Signed")

	if Signed == "" || To == "" || Symbol == "" {
		ret.Code = 1
		ret.Msg = "广播失败,参数错误"
		c.Data["json"] = ret
		c.ServeJSON()
		return
	}
	beego.Debug("转账广播", Symbol, "to:", To, "Signed:", Signed)
	//fmt.Println(string(c.Ctx.Input.RequestBody))
	Hash, err3 := models.SendActiveSigned(To, Symbol, Signed)
	if err3 != nil {

		ret.Code = 1
		ret.Msg = "广播失败:" + err3.Error()
		c.Data["json"] = ret
		c.ServeJSON()
		return
	}
	beego.Debug("广播成功", To, Symbol, Signed)
	ret.Code = 0
	ret.Msg = "广播成功"
	ret.Data = map[string]interface{}{
		"Hash": Hash,
	}

	c.Data["json"] = ret
	c.ServeJSON()
}

//获取个人地址列表
// @router /listaddressactive [get]
func (c *ActiveController) Listaddressactive() {

	var ret models.Response
	var uid int
	tokenString := c.Ctx.Input.Header("Authorization")
	uid, _ = models.ParseUidFromToken(tokenString)
	fmt.Println(uid)

	//fmt.Println(string(c.Ctx.Input.RequestBody))
	beego.Debug("获取转账支持币种")
	data, err := models.ORMActiveListAddress(uid)
	if err != nil {

		ret.Code = 1
		ret.Msg = err.Error()
		c.Data["json"] = ret
		c.ServeJSON()
		return
	}
	if len(data) <= 0 {
		ret.Data = []string{}
	} else {
		ret.Data = data
	}
	ret.Code = 0
	ret.Msg = ""
	c.Data["json"] = ret
	c.ServeJSON()
}
